﻿Imports ADOEntity
Imports System.Data

Partial Class Administrator_userList
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M66"
    Dim UserEntity As UserEntities
    Dim dsUser As New DataSet
    Dim clsQuery As clsDatabase
    Dim intBeforeItemIndex As Integer
    Dim clsDataTable As New clsLINQToDataTable
    Dim convertDate As New clsDateFormat
    Dim clsMasterDropDown As clsMasterDropDown
    Dim clsSessionMenuRight As clsSessionMenuRight
#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        'lbluserName.Text = Resources.resUser.userName
        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear
        btnPrint.Text = Resources.resButton.btnPrint

        lblActive.Text = Resources.resUser.isInactive
        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid



    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            UserEntity = New UserEntities
            clsMasterDropDown = New clsMasterDropDown

            clsSessionMenuRight = Session("ClsMenuRight")

            If (Not IsPostBack) Then
                LoadDataToDropdown()
                CreateControlMP()
                setUserRightButton()
                setdefaultData()

            Else
                dsUser = Session("dsTblMaster")
                gvUser.DataSource = dsUser.Tables("sUser")
                gvUser.DataBind()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        UserEntity = Nothing
        clsMasterDropDown = Nothing
        Session("dsTblMaster") = dsUser
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "ผู้ใช้งานระบบ"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLogSearch()
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        Response.Redirect("userEdit.aspx?Status=Add")
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
        If Not (gvUser.SelectedIndex = -1) Then
            Response.Redirect("userEdit.aspx?Status=Edit&strUserName=" + gvUser.Rows(gvUser.SelectedIndex).Cells(1).Text)
        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGrid + "')", True)

        End If
    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvUser.SelectedIndex = -1) Then
            Dim userName As String = gvUser.Rows(gvUser.SelectedIndex).Cells(1).Text
            Try
                UserEntity = New UserEntities
                Dim qry = (From sUser In UserEntity.SUSER Where sUser.USERNAME = userName).ToList
                If Not (qry(0).ISINACTIVE = True) Then
                    qry(0).ISINACTIVE = 1
                    UserEntity.SaveChanges()
                    IsDataBind()
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMessageAlert.alertRe_Editing + "')", True)
                End If

            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "userList")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub


#End Region

#Region "Even GridView"
    Protected Sub gvUser_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvUser.SelectedIndexChanged

        If (gvUser.SelectedIndex = intBeforeItemIndex) Then
            clearGvIndex()
        Else
            btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                                                                        IIf(gvUser.SelectedIndex = -1, "", gvUser.Rows(gvUser.SelectedIndex).Cells(1).Text)) + "');")

        End If
    End Sub

    Protected Sub gvUser_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvUser.SelectedIndexChanging
        intBeforeItemIndex = gvUser.SelectedIndex
    End Sub

    Protected Sub gvUser_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvUser.PageIndexChanging
        gvUser.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub gvUser_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvUser.Sorting
        Dim dt = TryCast(dsUser.Tables("sUser"), DataTable)

        If dt IsNot Nothing Then
            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvUser.DataSource = dsUser.Tables("sUser")
            gvUser.DataBind()
            clearGvIndex()
        End If
    End Sub


#End Region

#Region " Function"
    Private Sub setdefaultData()
        rdolActive.SelectedValue = 0
    End Sub

    Private Sub setUserRightButton()
        Dim col As New Collection
        col.Add(btnSearch, statusbtn.Query.ToString)
        col.Add(btnAdd, statusbtn.Add.ToString)
        col.Add(btnModify, statusbtn.Modify.ToString)
        col.Add(btnDelete, statusbtn.delete.ToString)
        col.Add(btnPrint, statusbtn.print.ToString)
        setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub


    Private Sub LoadDataToDropdown()
        Try
            clsMasterDropDown.setDeptToDdlSearch(ddlDepartment, _
                                                   strDeptCode:=clsSessionMenuRight.getDeptCode, _
                                                   strRoleCode:=clsSessionMenuRight.getRoleGroup)

            clsMasterDropDown.setUserRightToDdlSearch(ddlUserRight, clsSessionMenuRight.getRoleGroup, strDepCode:=ddlDepartment.SelectedValue)

            'clsMasterDropDown.setZoneToDdl(ddlZone, selectData:=strZoneCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, _
            '                            strZoneCode:=clsSessionMenuRight.getZoneCode, strDeptCode:=ddlDepartment.SelectedValue)


            clsMasterDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartment.SelectedValue, _
                                                       strBranchCode:=clsSessionMenuRight.getBranchCode, _
                                                 strRoleCode:=clsSessionMenuRight.getRoleGroup, _
                                                 strZoneCode:=clsSessionMenuRight.getZoneCode)
            ' Else
            ' ddlBranch.Enabled = False
            'end If


            'clsMasterDropDown.setBranchDdlSearch(ddlBranch, strRoleCode:=clsSessionMenuRight.getRoleGroup, _
            '                                    strBranchCode:=clsSessionMenuRight.getBranchCode, _
            '                                    strDeptCode:=clsSessionMenuRight.getDeptCode, _
            '                                     strZoneCode:=clsSessionMenuRight.getZoneCode)

        Catch ex As Exception
            WriteError(ex, "LoadDataToDropdown", "userList")
        End Try


    End Sub



    Private Sub clearGvIndex()
        gvUser.SelectedIndex = -1
        btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try
            Dim iCountUserBeforUr As Integer = 0
            Dim iCountUserBeforInactive As Integer = 0
            Dim clsSessionMenuRight As New clsSessionMenuRight
            clsSessionMenuRight = Session("ClsMenuRight")
            If dsUser.Tables.Contains("sUser") Then
                dsUser.Tables.Clear()
            End If

            Dim qryUser = From tbl_User In UserEntity.SUSER
                                Group Join tbl_Branch In UserEntity.SBRANCH On tbl_User.BRANCHCODE Equals tbl_Branch.BRANCHCODE Into tblLeftUr_br = Group
                                From tbluserLeftBr In tblLeftUr_br.DefaultIfEmpty Group Join tbl_Dept In UserEntity.SDEPARTMENT On tbl_User.DEPTCODE Equals tbl_Dept.DEPTCODE Into tblLeftDept = Group
                                From tblLeftBr_Dept In tblLeftDept.DefaultIfEmpty
                                  Join userRight In UserEntity.SUSERRIGHT On tbl_User.USERRIGHT Equals userRight.USERRIGHT
                                  Join tbl_role In UserEntity.SROLE On tbl_User.ROLECODE Equals tbl_role.ROLECODE
                            Order By tbl_User.USERNAME
                            Select tbl_User.USERNAME, tbl_User.EMPCODE, tbluserLeftBr.BRANCHNAME, tbl_User.BRANCHCODE,
                                  tbl_User.DEPTCODE, tblLeftBr_Dept.DEPTNAME, tbl_User.ROLECODE, tbl_User.PWDBEGINDATE,
                                  tbl_User.MUSTCHANGEPWD, userRight.USERRIGHT, userRight.USERRIGHTDESC, tbl_User.INACTIVEDATE, tbl_User.ISINACTIVE,
                                  tbl_User.EMPNAME, tbl_User.EMPLASTNAME, tbl_role.ROLENAME, tbl_User.ZONECODE




            If Not (txtUserName.Text = "") Then
                iCountUserBeforUr = qryUser.Where(Function(suser) suser.USERNAME = txtUserName.Text).Count
            End If

            If (clsSessionMenuRight.getRoleGroup > 89) Then
                'qryUser = qryUser.Where(Function(fn) fn.ROLECODE <= clsSessionMenuRight.getRoleGroup)
            ElseIf (clsSessionMenuRight.getRoleGroup > 79) Then
                qryUser = qryUser.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
            ElseIf (clsSessionMenuRight.getRoleGroup > 69) Then
                qryUser = qryUser.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
            ElseIf (clsSessionMenuRight.getRoleGroup > 59) Then
                qryUser = qryUser.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup And fn.ZONECODE = clsSessionMenuRight.getZoneCode)
            ElseIf (clsSessionMenuRight.getRoleGroup < 60) Then
                qryUser = qryUser.Where(Function(fn) fn.ROLECODE < clsSessionMenuRight.getRoleGroup)
            End If

            '---------------------------------------------------------------------------------------------


            If Not (txtUserName.Text = "") Then
                ' If txtUserName.Text.Trim.Length < 5 Then
                qryUser = qryUser.Where(Function(suser) suser.USERNAME.Contains(txtUserName.Text))
                'Else
                ' qryUser = qryUser.Where(Function(suser) suser.USERNAME = txtUserName.Text)
                ' End If
            End If

            If Not (txtFirstName.Text = "") Then
                qryUser = qryUser.Where(Function(suser) suser.EMPNAME.Contains(txtFirstName.Text))
            End If

            If Not (txtLastName.Text = "") Then
                qryUser = qryUser.Where(Function(suser) suser.EMPLASTNAME.Contains(txtLastName.Text))
            End If

            If Not (ddlUserRight.SelectedValue = "0") Then
                qryUser = qryUser.Where(Function(suser) suser.USERRIGHT = ddlUserRight.SelectedValue)
            End If

            If Not (ddlDepartment.SelectedValue = "0") Then
                qryUser = qryUser.Where(Function(suser) suser.DEPTCODE = ddlDepartment.SelectedValue)
            End If

            If Not (ddlBranch.SelectedValue = "0") Then
                qryUser = qryUser.Where(Function(suser) suser.BRANCHCODE = ddlBranch.SelectedValue)
            End If
            If Not (txtUserName.Text = "") Then
                iCountUserBeforInactive = qryUser.Count
            End If
            If Not (rdolActive.SelectedValue = -1) Then

                If (rdolActive.SelectedValue = 0) Then
                    qryUser = qryUser.Where(Function(suser) suser.ISINACTIVE = rdolActive.SelectedValue)
                Else
                    qryUser = qryUser.Where(Function(suser) suser.ISINACTIVE = rdolActive.SelectedValue)
                End If

            End If




            If qryUser.Count = 0 Then
                dsUser.Tables.Add(clsDataTable.LINQToDataTable(qryUser, "sUser").Copy)
                If (iCountUserBeforUr = 1) Then
                    lblMsgUser.Visible = True
                    lblMsg.Visible = False
                    lblMsgUser.Text = "รหัสผู้ใช้งานมีอยู่แล้วในระบบ แต่ไม่อยู่ภายใต้ฝ่ายหรือสาขา/ส่วนงาน ของท่าน"
                Else
                    lblMsgUser.Visible = False
                    lblMsg.Visible = True
                End If


                lblTotal.Text = ""

            Else
                qryUser = qryUser.Where(Function(suser) suser.USERNAME <> clsSessionMenuRight.getUserName)
                dsUser.Tables.Add(clsDataTable.LINQToDataTable(qryUser, "sUser").Copy)

                If (dsUser.Tables("sUser").Rows.Count = 0) Then
                    lblMsgUser.Visible = False
                    lblMsg.Visible = True
                Else
                    lblMsgUser.Visible = False
                    lblMsg.Visible = False
                    lblTotal.Text = "จำนวนรายการทั้งหมด " + dsUser.Tables("sUser").Rows.Count.ToString + " รายการ "
                End If
            End If


            gvUser.DataSource = dsUser.Tables("sUser")
            gvUser.DataBind()
            clearGvIndex()

            clsQuery = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "userList")
        End Try

    End Sub

    'Private Sub IsDataBind1()


    'End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub SaveLogSearch()
        Try

            Dim desc As String = ""

            If Not (ddlDepartment.SelectedValue = "0") Then
                desc += " ฝ่าย - " + ddlDepartment.SelectedItem.Text
            End If

            If Not (ddlBranch.SelectedValue = "0") Then
                desc += " ส่วนงาน/สาขา - " + ddlBranch.SelectedItem.Text
            End If

            If Not (ddlUserRight.SelectedValue = "0") Then
                desc += " กลุ่มสิทธิ์ - " + ddlUserRight.SelectedItem.Text
            End If

            If Not (txtUserName.Text = "") Then
                desc += " รหัสผู้ใช้งาน - " + txtUserName.Text
            End If

            If Not (txtFirstName.Text = "") Then
                desc += " ชื่อผู้ใช้งาน - " + txtFirstName.Text
            End If

            If Not (txtLastName.Text = "") Then
                desc += " นามสกุลผู้ใช้งาน - " + txtLastName.Text
            End If


            If Not (rdolActive.SelectedValue = -1) Then

                If (rdolActive.SelectedValue = 0) Then
                    desc += " สถานะ - " + "ใช้งาน"
                Else
                    desc += " สถานะ - " + "ไม่ใช้งาน"
                End If
            Else
                desc += " สถานะ - " + "ทั้งหมด"
            End If

            If Not desc = "" Then
                desc = "ค้นหาข้อมูลผู้ใช้งานระบบ จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M66")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลผู้ใช้งานระบบ"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M66")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region

    Protected Sub ddlDepartment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDepartment.SelectedIndexChanged
        Try
            Dim clsDropDown As New clsMasterDropDown
            clsSessionMenuRight = Session("ClsMenuRight")
            If Not (ddlDepartment.SelectedValue = "0") Then
                clsDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartment.SelectedValue, strBranchCode:=clsSessionMenuRight.getBranchCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, strZoneCode:=clsSessionMenuRight.getZoneCode)
                'clsMasterDropDown.setUserRightToDdlSearch(ddlUserRight, clsSessionMenuRight.getRoleGroup)

                clsDropDown.setUserRightToDdlSearch(ddlUserRight, strRoleCode:=clsSessionMenuRight.getRoleGroup, strDepCode:=ddlDepartment.SelectedValue)
            Else
                clsDropDown.setBranchDdlSearch(ddlBranch, strDeptCode:=ddlDepartment.SelectedValue, strBranchCode:=clsSessionMenuRight.getBranchCode, strRoleCode:=clsSessionMenuRight.getRoleGroup, strZoneCode:=clsSessionMenuRight.getZoneCode)
                clsDropDown.setUserRightToDdlSearch(ddlUserRight, strRoleCode:=clsSessionMenuRight.getRoleGroup)
                ddlBranch.SelectedValue = "0"
                ddlUserRight.SelectedValue = "0"
            End If
            clsDropDown = Nothing
        Catch ex As Exception
            WriteError(ex, "ddlDepartment_SelectedIndexChanged", "userList")
        End Try







    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        txtUserName.Text = ""

        txtFirstName.Text = ""
        txtLastName.Text = ""
        ddlUserRight.SelectedIndex = 0
        ddlDepartment.SelectedIndex = 0
        ddlBranch.SelectedIndex = 0

        lblMsg.Visible = False
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim param As String = "{ 'rptType' : '6'," _
                              & "'deptCode' : '" & ddlDepartment.SelectedValue & "/" & ddlDepartment.SelectedItem.Text & "'," _
                              & "'BranchCode' : '" & ddlBranch.SelectedValue & "/" & ddlBranch.SelectedItem.Text & "'," _
                              & "'userRight' : '" & ddlUserRight.SelectedValue & "/" & ddlUserRight.SelectedItem.Text & "'," _
                              & "'userName' : '" & txtUserName.Text.Trim & "'," _
                              & "'empName' : '" & txtFirstName.Text.Trim & "'," _
                              & "'empLastName' : '" & txtLastName.Text.Trim & "'," _
                              & "'isInactive' : '" & rdolActive.SelectedValue & "/" & rdolActive.SelectedItem.Text & "'}"

        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)

        SaveLogPrint()

    End Sub


End Class
